import React, { useState, useEffect } from 'react';
import { Card, Form, Row, Col, Input, Select, Button, Table, Popconfirm, message, Badge, Divider, DatePicker } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import PaymentDetail from './PaymentDetail';
import { withRouter } from 'react-router-dom';
import { formatBalance } from '@/utils/utils';
import { useDebounceFn, deepclone  } from '@/utils';
import { Storage } from '@/assets/js/storage';
import { TOKEN } from '@/utils/constant'
import moment from 'moment';
import './index.scss';
import { 
  rechargeList,
  rechargeListSum,
} from '@/api/trans'

const Deposit = (props) => {
  const [searchForm] = Form.useForm();
  const { RangePicker } = DatePicker;
  // 筛选数据
  const [values] = useState({
    userType: '-1',
    orderNo: '',
    account: '',
    minTransAmount: '',
    maxTransAmount: '',
    transId: '',
    transStatus: '-1',
    duelTypeId: '-1',
    rechargeTypeId:  '-1',
    remark: '',
    transRemark: '',
    arrivedTime: [],
    applyTime: [moment(),moment()],
    arrivedStartTime: null,
    arrivedEndTime: null,
    operateAccount: '',
  })
  // 存款状态
  const paymentStatus = [
    { value: '-1', label: '全部' },
    { value: 1, label: '审核中' },
    { value: 2, label: '交易成功' },
    { value: 3, label: '交易失败' },
  ]
  // 存款方式
  const receiptType = [
    { value: '-1', label: '全部' },
    { value: 'USDT', label: 'USDT' },
  ]
  
  const { history } = props
  // 显示详情
  const [showDetail, setShowDetail] = useState(false)
  const [detailParams, setDetailParams] = useState(null)
  // 分页
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  // 面包屑
  const breadcrumbList = ['财务管理', '存款管理']
  // 布局
  const layout1 = { sm: 24, md: 12, lg: 12, xl: 6, xxl: 6 };
  const labelCol = { sm: 24, md: 8, lg: 8, xl: 8 };
  const wrapperCol = { sm: 24, md: 16, lg: 16, xl: 16 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 24, xxl: 24 };
  
  const [formData, setFormData] = useState(values)
  let [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([]);
  const [pageSum, setPageSum] = useState(0)
  const [allSum, setAllSum] = useState(0)
  // 表单头部
  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户账号',
      dataIndex: 'account',
      key: 'account',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户编号',
      dataIndex: 'userCode',
      key: 'userCode',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户名称',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      align: 'center',
      width: 110,
      render: (text: any) => text || '--',
    },
    {
      title: '到账时间',
      dataIndex: 'receiptTime',
      key: 'receiptTime',
      align: 'center',
      width: 110,
      render: (text: any) => text || '--',
    },
    {
      title: '申请金额',
      dataIndex: 'applyAmount',
      key: 'applyAmount',
      align: 'center',
    },
    {
      title: '到账金额',
      dataIndex: 'receiptAmount',
      key: 'receiptAmount',
      align: 'center',
    },
    {
      title: '手续费',
      dataIndex: 'fee',
      key: 'fee',
      align: 'center',
    },
    {
      title: '交易信息',
      dataIndex: 'arrivedTime',
      key: 'arrivedTime',
      align: 'center',
      width: 200,
      render: (text: any, record: any) => {
        if (record.transName === '人工充值') {
          return `通过 人工充值 ${formatBalance(record.applyAmount, 3) || '--'}元`;
        } else {
          return `通过 ${record.transName} 存入
           ${formatBalance(record.applyAmount, 3) || '--'}元到账户 ${record.transAddress || '--'}`;
        }
      },
    },
    {
      title: '交易状态',
      dataIndex: 'transStatus',
      key: 'transStatus',
      align: 'center',
      render: (text: string, record: any) => {
        switch (record.transStatus) {
          case 1:
            return <Badge status="processing" text="审核中" />;
            break;
          case 2:
            return <Badge status="success" text="交易成功" />;
            break;
          default:
            return <Badge status="error" text="交易失败" />;
            break;
        }
      },
    },
    {
      title: '操作人',
      key: 'operator',
      dataIndex: 'operator',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        if (record.transStatus === 1) {
          return (
            <span>
              <a
                onClick={() => {
                  goDetail({
                    edit: true,
                    id: record.orderNo
                  })
                }}
              >
                审核
              </a>
            </span>
          );
        } else {
          return <>
              <a
                onClick={() => {
                  goDetail({
                    edit: false,
                    id: record.orderNo
                  })
                }}
              >
                查看
              </a>
          </>;
        }
      },
    }
    
    
    
    
  ];
  
  // 提交弹框表单做防抖处理
  const handleSubmit = useDebounceFn((values) => {
    console.log(values,'valuesvalues');
    onFinish(values)
    getAll(values)
  }, 1500, true);
  const onFinish = async (values) => {
    let formData = {}
    for (let key in values) {
      if (values[key] && values[key] !== '-1') {
        formData[key] = values[key]
      }
    }
    try {
      let params = {
        ...formData,
        startApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[0]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        endApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[1]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        startReceiptTime: formData&&formData.arrivedTime[0] ? moment(formData.arrivedTime[0]).format("YYYY-MM-DD") : '',
        endReceiptTime: formData&&formData.arrivedTime[1] ? moment(formData.arrivedTime[1]).format("YYYY-MM-DD") : '',
        pageSize,
        currentPage,
      }
      delete params.applyTime
      delete params.arrivedTime
      setLoading(true)
      let res = await rechargeList(params)
      if(res.code === 0) {
        if(res.data.records){
          let all = 0;
          res.data.records.forEach(item=>{
            all += parseFloat(item.applyAmount);
          })
          setPageSum(all)
        }
        setDataSource(res.data.records || [])
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  const getAll = async (values) => {
    let formData = {}
    for (let key in values) {
      if (values[key] && values[key] !== '-1') {
        formData[key] = values[key]
      }
    }
    try {
      let params = {
        ...formData,
        startApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[0]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        endApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[1]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
        startReceiptTime: formData&&formData.arrivedTime[0] ? moment(formData.arrivedTime[0]).format("YYYY-MM-DD") : '',
        endReceiptTime: formData&&formData.arrivedTime[1] ? moment(formData.arrivedTime[1]).format("YYYY-MM-DD") : '',
        pageSize,
        currentPage,
      }
      delete params.applyTime
      delete params.arrivedTime
      setLoading(true)
      let res = await rechargeListSum(params)
      if(res.code === 0) {
        setAllSum(res.data)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  const exportExcel = async () => {
    let val = {}
    let values = deepclone(formData)
    for (let key in values) {
      if (values[key] && values[key] !== '-1') {
        val[key] = values[key]
      }
    }
    let params = {
      ...val,
      startApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[0]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
      endApplyTime: formData&&formData.applyTime ? moment(formData.applyTime[1]).format("YYYY-MM-DD") : moment().format("YYYY-MM-DD"),
      startReceiptTime: formData&&formData.arrivedTime[0] ? moment(formData.arrivedTime[0]).format("YYYY-MM-DD") : '',
      endReceiptTime: formData&&formData.arrivedTime[1] ? moment(formData.arrivedTime[1]).format("YYYY-MM-DD") : '',
      pageSize,
      currentPage,
    }
    delete params.applyTime
    delete params.arrivedTime
    console.log(params)
    let webSide = 1;
    let token = Storage.get(TOKEN);
    let Authorization = 'Bearer ' + token;
    let excel = `${window.location.origin}/trans/rechargeExport`;
    fetch(excel, {
      method: 'post',
      params,
      headers: new Headers({
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        Authorization,
        webSide
      }),
    })
    .then(response => response.blob())
    .then(blob => {
      if(blob.type == "application/json") {
        let reader: any = new FileReader(); // 创建读取文件对象
        reader.readAsText(blob, 'utf-8');
        reader.addEventListener("loadend", () => {
          let res = JSON.parse(reader.result);
          message.error(res.msg);
        });
        return;
      }
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = '商户出款记录';
      a.click();
      window.URL.revokeObjectURL(url);
    });
  };
  // 首次更新
  useEffect(() => {
    onFinish(formData)
    getAll(formData)
    return () => { 
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  const goDetail  = (data) => {
    setDetailParams(data);
    setShowDetail(true);
  }
  // 初始化
  return (
  <div>
    {
      showDetail === false
      ?
      <div>
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className='agent-main'>
        <Form
          initialValues={values} 
          form={searchForm} 
          onFinish={(val) => {
            handleSubmit(val)
          }}>
            <Card className="formCard" style={{ width: '100%' }} bordered={false}>
              <Row>
                <Col {...layout1}>
                  <Form.Item
                    name="applyTime"
                    className="formItem"
                    label="申请时间"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <RangePicker style={{width:'100%'}} />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="arrivedTime"
                    className="formItem"
                    label="到账时间"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <RangePicker style={{width:'100%'}} />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="account"
                    className="formItem"
                    label="商户账号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入商户账号" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="orderNo"
                    className="formItem"
                    label="订单编号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="请输入订单编号" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="transStatus"
                    className="formItem"
                    label="存款状态"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select
                      options={paymentStatus}
                    />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="duelTypeId"
                    className="formItem"
                    label="存款方式"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select
                      options={receiptType}
                    />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="minTransAmount"
                    className="formItem"
                    label="最小交易金额"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入最小交易金额" />
                  </Form.Item>
                </Col>
                <Col {...layout1}>
                  <Form.Item
                    name="maxTransAmount"
                    className="formItem"
                    label="最大交易金额"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入最大交易金额" />
                  </Form.Item>
                </Col>
                {/* <Col {...layout1}>
                  <Form.Item
                    name="transId"
                    className="formItem"
                    label="交易号"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入交易号" />
                  </Form.Item>
                </Col> */}
                <Col {...layout1}>
                  <Form.Item
                    name="operateAccount"
                    className="formItem"
                    label="操作人"
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear placeholder="输入操作人" />
                  </Form.Item>
                </Col>
                <Col {...layoutbtn}>
                  <span className="buttonLeft">
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                    <Button
                      className="reset-btn"
                      type="default"
                      onClick={() => {
                        searchForm.resetFields()
                      }}
                    >
                      重置
                    </Button>
                    <Button
                      className="reset-btn"
                      type="primary" 
                      onClick={()=>{exportExcel()}}>
                      导出
                    </Button>
                  </span>
                </Col>
              </Row>
            </Card>
          </Form>
          <div className='table-box'>
            <Card>
              <div className='table'>
                <Table
                  loading={loading}
                  size='middle'
                  bordered
                  scroll={{ x: 1224 }}
                  rowKey={'id'}
                  className='antd-table'
                  dataSource={dataSource}
                  pagination={{
                    size: 'default',
                    current: currentPage,
                    total: total,
                    showSizeChanger: true,
                    pageSize: pageSize,
                    onChange: (page, pagesize) => {}
                  }}
                  columns={columns} />
              </div>
              <div className="bottom">
                <span>总金额：{allSum}</span>
                <span>当前页汇总金额：{pageSum}</span>
              </div>
            </Card>
          </div>
        </div>
      </div>
      :
      <PaymentDetail detailParams={detailParams} back={()=>{setShowDetail(false)}} />
    }
  </div>
  )
}
export default withRouter(Deposit)